﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;

namespace BW.Mes.WinForms.BasicData
{
    public partial class UpdateSupplierForm : DevExpress.XtraEditors.XtraForm
    {
        private SupplierForm.SupplierModel _model;
        private readonly HttpClient _httpClient = new HttpClient();
        private readonly string _apiBaseUrl = "https://localhost:7274";
        
        public UpdateSupplierForm(SupplierForm.SupplierModel model)
        {
            InitializeComponent();
            _model = model;
            // 反填
            textEditCode.Text = model.SupplierCode;
            textEditName.Text = model.SupplierName;
            textEditAbbreviation.Text = model.Abbreviation;
            textEditPhone.Text = model.Phone;
            textEditAddress.Text = model.Address;
            textEditUSCC.Text = model.USCC;
            textEditMsg.Text = model.SupplierMsg;
        }
        
        public UpdateSupplierForm()
        {
            InitializeComponent();
        }
        
        private async void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                // 数据验证
                if (string.IsNullOrWhiteSpace(textEditCode.Text))
                {
                    XtraMessageBox.Show("供应商编号不能为空！", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    textEditCode.Focus();
                    return;
                }
                
                if (string.IsNullOrWhiteSpace(textEditName.Text))
                {
                    XtraMessageBox.Show("供应商名称不能为空！", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    textEditName.Focus();
                    return;
                }

                var model = new
                {
                    Id = _model.Id,
                    SupplierCode = textEditCode.Text.Trim(),
                    SupplierName = textEditName.Text.Trim(),
                    Abbreviation = textEditAbbreviation.Text?.Trim(),
                    Phone = textEditPhone.Text?.Trim(),
                    Address = textEditAddress.Text?.Trim(),
                    USCC = textEditUSCC.Text?.Trim(),
                    SupplierMsg = textEditMsg.Text?.Trim(),
                    UpdatedAt = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")
                };
                
                string jsonData = JsonConvert.SerializeObject(model);
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                
                var response = await _httpClient.PutAsync($"{_apiBaseUrl}/api/Supplier/UpdateSupplier", content);
                var responseContent = await response.Content.ReadAsStringAsync();
                
                if (response.IsSuccessStatusCode)
                {
                    // 尝试解析API响应
                    try
                    {
                        var apiResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                        if (apiResult != null)
                        {
                            if (apiResult.success == 1)
                            {
                                Console.WriteLine($"[UpdateSupplierForm] 修改成功，准备关闭窗口。API返回：success=1, message={apiResult.message}");
                                XtraMessageBox.Show("修改成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                this.DialogResult = DialogResult.OK;
                                this.Close();
                            }
                            else
                            {
                                Console.WriteLine($"[UpdateSupplierForm] 修改失败，API返回：success={apiResult.success}, message={apiResult.message}");
                                string errorMessage = apiResult.message ?? "修改失败，未知错误";
                                XtraMessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else
                        {
                            Console.WriteLine("[UpdateSupplierForm] API响应无法解析，修改失败");
                            XtraMessageBox.Show("修改失败，未知错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    catch (JsonException)
                    {
                        // 如果无法解析为ApiResult格式，则按原逻辑处理
                        XtraMessageBox.Show("修改成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                }
                else
                {
                    string errorMessage = $"HTTP错误：{response.StatusCode}";
                    try
                    {
                        var apiResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                        if (apiResult != null && !string.IsNullOrEmpty(apiResult.message))
                        {
                            errorMessage = apiResult.message;
                        }
                    }
                    catch
                    {
                        // 如果无法解析错误信息，使用默认错误信息
                    }
                    
                    XtraMessageBox.Show($"修改失败：{errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (HttpRequestException ex)
            {
                XtraMessageBox.Show($"网络连接错误：{ex.Message}", "连接错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (TaskCanceledException ex)
            {
                XtraMessageBox.Show("请求超时，请检查网络连接", "超时错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"修改过程中发生错误：{ex.Message}", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}